<?php
/**
 * Created by PhpStorm.
 * User: 万奇
 * Date: 2020/11/23 0023
 * Time: 19:10
 */

namespace app\core;

use app\admin\model\WxkConfig;
use think\facade\Cache;

class Wechat
{
    private $get_token_url                  = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'; // 获取 token
    private $department_list_url            = 'https://qyapi.weixin.qq.com/cgi-bin/department/list'; // 获取企业微信部门列表
    private $user_list_url                  = 'https://qyapi.weixin.qq.com/cgi-bin/user/list'; // 获取企业微信获取部门成员
    private $client_user_all_info_url       = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user'; // 根据成员批量获取客户详情
    private $client_user_list_url           = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list'; // 根据成员批量获取客户详情
    private $add_corp_tag_url               = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag'; // 添加企业微信客户标签
    private $get_corp_tag_list_url          = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list'; // 添加企业微信客户标签
    private $get_new_external_userid_url    = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_new_external_userid';//external_userid转换
    private $transfer_customer_url          = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/transfer_customer';//分配在职成员的客户
    private $transfer_result_url            = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/transfer_result';//客户分配结果查询
    private $group_chat_job_transfer_url    = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/onjob_transfer';//分配在职成员的客户群
    private $get_unassigned_list_url        = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_unassigned_list';//获取离职成员的客户列表
    private $resigned_transfer_customer_url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/resigned/transfer_customer';//分配离职成员的客户
    private $resigned_transfer_result_url   = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/resigned/transfer_result';//查询离职成员的客户分配情况
    private $group_chat_transfer_url        = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/transfer';//将已离职成员为群主的群，分配给另一个客服成员

    /**
     * 根据不同业务获取不同 access_token
     * User: 万奇
     * Date: 2020/11/24 0024
     * @param $type - 业务类型格式：（根据企业微信数据库表字段）
     * @return mixed
     */
    private function get_access_token($type)
    {
        $access_token = Cache::get('access_token_' . $type);
        if ($access_token) {
            return $access_token;
        }

        $model   = new WxkConfig();
        $qy_info = $model->get_qy_info();

        if (!$qy_info) {
            response(500, '未查到该企业微信配置');
        }

        $access_token = json_decode(curl_request($this->get_token_url, ['corpid' => $qy_info['wxk_id'], 'corpsecret' => $qy_info[$type]], [], false), true);

        if (!isset($access_token['access_token'])) {
            response(500, 'access_token 获取失败！');
        }

        Cache::set('access_token_' . $type, $access_token['access_token'], $access_token['expires_in'] - 100);

        return $access_token['access_token'];
    }

    /**
     * 企业微信api请求接口
     * User: 万奇
     * Date: 2020/12/4 0004
     * @param       $url_name    -接口地址
     * @param       $secret_type - secret类型
     * @param array $data        - 数据
     * @param bool  $is_post     - 请求方式
     * @param bool  $get_token   - 是否get方式传参（默认否）
     * @return mixed
     */
    public function request_wechat_api($url_name, $secret_type, $data = [], $is_post = true, $get_token = false)
    {
        $access_token = $this->get_access_token($secret_type);
        $get_token ? $url_name = $url_name . '?access_token=' . $access_token : $data['access_token'] = $access_token;

        return json_decode(curl_request($url_name, $data, [], $is_post), true);
    }

    /**
     * 根据成员批量获取客户详情
     * User: 万奇
     * Date: 2020/11/29 0029
     * @param       $param
     * @param array $data
     * @return mixed
     */
    public function get_client_all_info($param, $data = [])
    {
        $access_token = $this->get_access_token($param['type']);

        $result = json_decode(curl_request($this->client_user_all_info_url . '?access_token=' . $access_token, $data, []), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }

        return $result;
    }

    /**
     * 按部门获取企业微信成员
     * User: 万奇
     * Date: 2020/11/25 0025
     * @param       $param
     * @param array $data
     * @return mixed
     */
    public function get_user_simple_list($param, $data = [])
    {
        $access_token         = $this->get_access_token($param['type']);
        $data['access_token'] = $access_token;

        $result = json_decode(curl_request($this->user_list_url, $data, [], false), true);

        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }

        return $result['userlist'];
    }

    /**
     * 获取企业微信部门列表
     * User: 万奇
     * Date: 2020/11/25 0025
     * @param $param
     * @param $data
     * @return mixed
     */
    public function get_department_list($param, $data = [])
    {
        $access_token         = $this->get_access_token($param['type']);
        $data['access_token'] = $access_token;
        $result               = json_decode(curl_request($this->department_list_url, $data, [], false), true);

        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }

        return $result['department'];
    }

    /**
     * 添加企业微信标签
     * User: 万奇
     * Date: 2020/11/24 0024
     * @param $param
     * @param $data
     * @return bool
     */
    public function add_corp_tag($param, $data)
    {
        $access_token         = $this->get_access_token($param['type']);
        $data['access_token'] = $access_token;

        $result = json_decode(curl_request($this->add_corp_tag_url, $data), true);

        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }

        return true;
    }

    /**
     * @param $access_token string 代开发应用access_token
     * @param $user_ids     array 客户external_userid
     * @return mixed
     */
    public function get_new_external_userid($access_token, $user_ids)
    {
        $result = json_decode(curl_request($this->get_new_external_userid_url . '?access_token=' . $access_token, ['external_userid_list' => $user_ids]), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param $handover_userid      string 原跟进成员的userid
     * @param $takeover_userid      string 接替成员的userid
     * @param $external_userid      array 客户的external_userid列表，每次最多分配100个客户
     * @param $transfer_success_msg string 转移成功后发给客户的消息，最多200个字符，不填则使用默认文案
     * @return true
     */
    public function transfer_customer(string $handover_userid, string $takeover_userid, array $external_userid = [], string $transfer_success_msg = "")
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'handover_userid'      => $handover_userid,
            'takeover_userid'      => $takeover_userid,
            'external_userid'      => $external_userid,
            'transfer_success_msg' => $transfer_success_msg
        ];
        $result       = json_decode(curl_request($this->transfer_customer_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param string $handover_userid 原跟进成员的userid
     * @param string $takeover_userid 接替成员的userid
     * @param string $cursor          分页查询的cursor，每个分页返回的数据不会超过1000条；不填或为空表示获取第一个分页；
     * @return mixed
     */
    public function transfer_result(string $handover_userid, string $takeover_userid, string $cursor = '')
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'handover_userid' => $handover_userid,
            'takeover_userid' => $takeover_userid,
            'cursor'          => $cursor
        ];
        $result       = json_decode(curl_request($this->transfer_result_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param array  $chat_id_list 需要转群主的客户群ID列表。取值范围： 1 ~ 100
     * @param string $new_owner    新群主ID
     * @return void
     */
    public function group_chat_job_transfer(array $chat_id_list, string $new_owner)
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'chat_id_list' => $chat_id_list,
            'new_owner'    => $new_owner
        ];
        $result       = json_decode(curl_request($this->group_chat_job_transfer_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param int    $limit  每次返回的最大记录数，默认为1000，最大值为1000
     * @param string $cursor 分页查询游标，字符串类型，适用于数据量较大的情况，如果使用该参数则无需填写page_id，该参数由上一次调用返回
     * @return mixed
     */
    public function get_unassigned_list(int $limit = 100, string $cursor = '')
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'cursor' => $cursor,
            'limit'  => $limit
        ];
        $result       = json_decode(curl_request($this->get_unassigned_list_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param string $handover_userid 原跟进成员的userid
     * @param string $takeover_userid 接替成员的userid
     * @param array  $external_userid 客户的external_userid列表，每次最多分配100个客户
     * @return void
     */
    public function resigned_transfer_customer(string $handover_userid, string $takeover_userid, array $external_userid)
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'handover_userid' => $handover_userid,
            'takeover_userid' => $takeover_userid,
            'external_userid' => $external_userid
        ];
        $result       = json_decode(curl_request($this->resigned_transfer_customer_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param string $handover_userid 原跟进成员的userid
     * @param string $takeover_userid 接替成员的userid
     * @param string $cursor          分页查询的cursor，每个分页返回的数据不会超过1000条；不填或为空表示获取第一个分页；
     * @return mixed
     */
    public function resigned_transfer_result(string $handover_userid, string $takeover_userid, string $cursor = '')
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'handover_userid' => $handover_userid,
            'takeover_userid' => $takeover_userid,
            'cursor'          => $cursor
        ];
        $result       = json_decode(curl_request($this->resigned_transfer_result_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

    /**
     * @param array  $chat_id_list 需要转群主的客户群ID列表。取值范围： 1 ~ 100
     * @param string $new_owner    新群主ID
     * @return mixed
     */
    public function group_chat_transfer(array $chat_id_list, string $new_owner)
    {
        $access_token = $this->get_access_token("wxk_customer_admin_secret");
        $data         = [
            'chat_id'   => $chat_id_list,
            'new_owner' => $new_owner
        ];
        $result       = json_decode(curl_request($this->group_chat_transfer_url . '?access_token=' . $access_token, $data), true);
        if ($result['errcode'] != 0) {
            response(500, '操作失败');
        }
        return $result;
    }

}